'use strict';
const {
  validateBody,
  isLength,
  presence,
} = require('property-validator');
const bcrypt = require('bcryptjs');
const RecomeData = require('@utils/recomeData');
const { ParameterException } = require('@utils/http-exception');

async function registerValidate(ctx) {
  const { valid, errors } = validateBody(ctx.request, [
    isLength('username', { min: 4, max: 32 }, '账户长度为4至32个字符'),
    isLength('password1', { min: 4, max: 32 }, '密码长度为4至32个字符'),
    isLength('password2', { min: 4, max: 32 }, '确认密码长度为4至32个字符'),
  ]);
  if (!valid) {
    throw new ParameterException(errors);
  }
  const v = new RecomeData(ctx);
  if (v.get('body.password1') !== v.get('body.password2')) {
    throw new ParameterException('两次密码不一致');
  }
  return v;
}

async function loginValidate(ctx) {
  const { valid, errors } = validateBody(ctx.request, [
    isLength('username', { min: 4, max: 32 }, '账户长度为4至32个字符'),
    isLength('password', { min: 4, max: 32 }, '密码长度为4至32个字符'),
  ]);
  const v = new RecomeData(ctx);
  if (!valid) {
    throw new ParameterException(errors);
  }
  const user = await ctx.service.users.getUser(v.get('body.username'));
  if (!user) {
    throw new ParameterException('账户不存在');
  }
  const correct = bcrypt.compareSync(
    v.get('body.password'),
    user.getDataValue('password')
  );
  if (!correct) {
    throw new ParameterException('密码不正确');
  }
  user.update({
    signTime: ctx.helper.nowTime(),
  });
  await user.save();
  return user;
}

async function userDetailValidate(ctx) {
  const user = await ctx.service.users.getUser(ctx.username);
  if (!user) {
    throw new ParameterException('账户不存在');
  }
  return user;
}

/**
 * 电话验证
 * @param {}} name
 */
function validatePhone(name) {
  return function(subject) {
    const reg = new RegExp(
      '^1(3([0-35-9]\\d|4[1-8])|4[14-9]\\d|5([0-35689]\\d|7[1-79])|66\\d|7[2-35-8]\\d|8\\d{2}|9[13589]\\d)\\d{7}$'
    );
    const result = reg.test(subject[name]);
    let message = '电话不符合要求';
    if (result) {
      message = 'ok';
    }
    return {
      result,
      message,
      field: name,
    };
  };
}

async function userEditValidate(ctx) {
  const { valid, errors } = validateBody(ctx.request, [
    presence('avatar', '头像不能为空'),
    validatePhone('phone'),
  ]);
  if (!valid) {
    throw new ParameterException(errors);
  }
  return new RecomeData(ctx);
}

module.exports = {
  registerValidate,
  loginValidate,
  userDetailValidate,
  userEditValidate,
};
